import { createRouter, createWebHashHistory } from 'vue-router'
import Index from '@/views/index/index.vue'
import { useFeishuStore } from '@/stores/feishu'



const globalVal = globalThis as any

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/home',
      name: 'Index',
      component: Index,
      meta: {
        keepAlive: true
      }
    },

    {
      path: '/',
      alias: '/feishu',
      name: 'Feishu',
      component: () => import('@/views/feishu/selection/index.vue'),
      meta: {
        keepAlive: true
      }
    },
    {
      path: '/category',
      name: 'Category',
      component: () => import('@/views/feishu/category/index.vue'),
      meta: {
        keepAlive: true
      }
    },
    {
      path: '/daily',
      name: 'Daily',
      component: () => import('@/views/feishu/daily/index.vue'),
      meta: {
        keepAlive: true
      }
    },
    {
      path: '/preference',
      name: 'Preference',
      component: () => import('@/views/feishu/preference/index.vue'),
      meta: {
        keepAlive: true
      }
    },
    {
      path: '/script',
      name: 'Script',
      component: () => import('@/views/feishu/script/index.vue'),
      meta: {
        keepAlive: true
      }
    },
    {
      path: '/syt',
      name: 'Syt',
      component: () => import('@/views/syt/index.vue'),
      meta: {
        keepAlive: true
      }
    },
    {
      path: '/kuaishou',
      name: 'Kuaishou',
      component: () => import('@/views/kuaishou/index.vue'),
      meta: {
        keepAlive: true
      }
    },

    {
      path: '/:pathMatch(.*)*', // 捕获所有路径
      name: 'NotFound',
      component: () => import('@/views/error/404.vue')
    }
  ]
})

// 上一个路由
let prevRoute: any | null = null
router.beforeEach((to, from, next) => {
  const prevFullPath = prevRoute && prevRoute.from ? prevRoute.from.fullPath : ''
  if (prevFullPath == to.fullPath) {
    prevRoute = null
  } else {
    prevRoute = { from, to }
  }

  const feishuStore = useFeishuStore()
  feishuStore.initialize().then(()=>{
    next()
  })
})

globalVal.navigateTo = (config: any) => {
  const route = router.currentRoute.value
  if (route && route.fullPath === config.url) {
    return
  }
  const prevFullPath = prevRoute && prevRoute.from ? prevRoute.from.fullPath : ''

  // 如果同一个path 只是参数不一样，直接使用replace
  if (route && route.path == config.url.split('?')[0]) {
    router.replace(config.url)
  } else if (prevFullPath === config.url) {
    router.back()
  } else {
    router.push(config.url)
  }
}

globalVal.back = () => {
  if (globalVal.history.state.back === null) {
    router.replace('/')
  } else {
    router.back()
  }
}

export default router
